//
//  TMHomePageController.m
//  国学商家管理
//
//  Created by mac on 2018/6/19.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "TMHomePageController.h"
#import "TMHomeHeadView.h"
#import "TMHomeOthersCell.h"
#import "TMScanResultController.h"
#import "SLBarCodeViewController.h"
#import "TMSearchViewC.h"
#import "SDCycleScrollView.h"
#import "TMADCell.h"
#import "TMPoiResultCell.h"
#import "TMSearchController.h"
#import "TMCommodityDetailController.h"
#import "TMShopHomeController.h"
#import "TMItemPageController.h"
#import "TMHomeViewModel.h"
#import "TMBarnerModel.h"
#import "TMRecommendModel.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import "DXLAddressPickView.h"
@interface TMHomePageController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,AMapLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *homeTab;
@property (nonatomic, strong) TMSearchViewC *searchVC;
@property (nonatomic, strong) NSMutableArray *adimageURLs;
@property (nonatomic, strong) NSMutableArray *recommendArray;
@property (nonatomic, strong) NSMutableArray *localArray;

@property (nonatomic, strong) SDCycleScrollView *adView;
@property (nonatomic, strong) NSArray *adList;
@property (nonatomic, strong) NSArray *types;

@property (nonatomic, strong) TMHomeViewModel *viewModel;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) NSString* coor2d;

@property (nonatomic, strong) CLGeocoder *geoC;
@property (nonatomic, strong) DXLAddressPickView *pickerView;

@end

@implementation TMHomePageController

- (NSMutableArray *)recommendArray {
    if (!_recommendArray) {
        _recommendArray = [NSMutableArray array];
    }
    return _recommendArray;
}
- (NSMutableArray *)localArray {
    if (!_localArray) {
        _localArray = [NSMutableArray array];
    }
    return _localArray;
}
- (NSArray *)types {
    if (!_types) {
        _types = [NSArray array];
    }
    return _types;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     [self.homeTab.mj_header beginRefreshing];
    [UIView animateWithDuration:.25 animations:^{
        _searchVC.frame = CGRectMake(0, 0, kWindowW, 44);
        [self.navigationController.navigationBar addSubview:_searchVC];
    }];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [UIView animateWithDuration:.25 animations:^{
        [_searchVC removeFromSuperview];
    }];
}
- (CLGeocoder *)geoC
{
    if (!_geoC) {
        _geoC = [[CLGeocoder alloc] init];
    }
    return _geoC;
}
- (void)geoCode:(NSString *)address {
    
    //    NSString *address = self.shopAddress.text;
    
    // 容错处理
    if([address length] == 0)
    {
        return;
    }
    
    // 根据地址关键字, 进行地理编码
    [self.geoC geocodeAddressString:address completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        /**
         *  CLPlacemark : 地标对象
         *  location : 对应的位置对象
         *  name : 地址全称
         *  locality : 城市
         *  按相关性进行排序
         */
        CLPlacemark *pl = [placemarks firstObject];
        
        if(error == nil)
        {
            NSLog(@"%f----%f", pl.location.coordinate.latitude, pl.location.coordinate.longitude);
            self.latitude = [NSString stringWithFormat:@"%f",pl.location.coordinate.latitude];
            self.longitude = [NSString stringWithFormat:@"%f",pl.location.coordinate.longitude];
            self.coor2d = [NSString stringWithFormat:@"[%@,%@]",self.latitude,self.longitude];
            [self.homeTab.mj_header beginRefreshing];
            NSLog(@"%@", pl.name);
//            self.longitudeTf.text = [NSString stringWithFormat:@"%f,%f",pl.location.coordinate.latitude,pl.location.coordinate.longitude];
        }else{

//            self.longitudeTf.text = nil;
//            [self.param removeObjectForKey:@"lat_long"];
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.homeTab.delegate = self;
    self.homeTab.dataSource = self;
    [self geoCode:@"北京市东城区"];
    self.viewModel = [[TMHomeViewModel alloc]init];
    [self displayLocationManager];
    [self registerCells];
    [self displayNavgationItem];
    self.homeTab.tableFooterView = [UIView new];
    self.homeTab.backgroundColor = [UIColor whiteColor];
   // self.viewModel = [[TMHomeViewModel alloc]init];
    
    self.homeTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.viewModel getHomePageDataWithParam:self.coor2d Success:^(id respon1, id respon2) {
            self.adList = respon1[0];
            [self loadMainADdata];
//            self.recommendArray = respon1[1];
//            self.localArray = respon1[2];
//            self.types = respon1[3];
            self.localArray = respon1;
            [self.homeTab reloadData];
            [self.homeTab.mj_header endRefreshing];
        } Failed:^(NSString *error) {
            [self.homeTab.mj_header endRefreshing];
        }];
    }];
//    [self.homeTab.mj_header beginRefreshing];
}

- (void)registerCells{
    [self.homeTab registerNib:[UINib nibWithNibName:@"TMPoiResultCell" bundle:nil] forCellReuseIdentifier:@"TMPoiResultCell"];
    [self.homeTab registerNib:[UINib nibWithNibName:@"TMHomeOthersCell" bundle:nil] forCellReuseIdentifier:@"TMHomeOthersCell"];
    [self.homeTab registerClass:[TMADCell class] forCellReuseIdentifier:@"TMADCell"];
}
- (void)displayNavgationItem{
    __weak typeof(self) weakSelf =  self;
    _searchVC = [[NSBundle mainBundle] loadNibNamed:@"TMSearchViewC" owner:nil options:nil][0];
    _searchVC.frame = CGRectMake(0, 0, kWindowW, 44);
    [self.navigationController.navigationBar addSubview:_searchVC];
    __weak typeof(self) weakself = self;
    _searchVC.tapBlock = ^{
        TMSearchController *vc = [[UIStoryboard storyboardWithName:@"Home" bundle:nil] instantiateViewControllerWithIdentifier:@"TMSearchController"];
        [weakself.navigationController pushViewController:vc animated:YES];
    };
    _searchVC.scanBlock = ^{
        SLBarCodeViewController *vc = [[UIStoryboard storyboardWithName:@"QRCode" bundle:nil] instantiateViewControllerWithIdentifier:@"SLBarCodeViewController"];
        [weakself.navigationController pushViewController:vc animated:YES];
    };
    _searchVC.addressBlock = ^{
        [weakSelf leftAction];
    };
    
}
#pragma --mark sdcycle view
- (NSMutableArray *)adimageURLs {
    if (!_adimageURLs) {
        self.adimageURLs = [NSMutableArray array];
    }
    return _adimageURLs;
}
-(SDCycleScrollView *)adView {
    if (_adView ==nil) {
        _adView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kWindowW, kWindowW*(140.0/375.0)) delegate:self placeholderImage:[UIImage imageNamed:@"登录背景"]];
        _adView.backgroundColor = [UIColor whiteColor];
    }
    return _adView;
}
#pragma mark--首页广告
- (void)loadMainADdata{
    [self.adimageURLs removeAllObjects];
    for (TMBarnerModel *adModel in self.adList) {
        [self.adimageURLs addObject:[NSString stringWithBaseUrl:adModel.pic]];
    }
    if (self.adList.count >1 ) {
        self.adView.autoScroll = YES;
        self.adView.autoScrollTimeInterval = 4.0f;
    } else {
        self.adView.autoScroll = NO;

    }
    self.adView.showPageControl = self.adList.count > 1 ? YES : NO;
    self.adView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    self.adView.imageURLStringsGroup = self.adimageURLs;
    self.adView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
}
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    TMBarnerModel *model = self.adList[index];
    TMCommodityDetailController *vc = [[UIStoryboard storyboardWithName:@"Nearby" bundle:nil] instantiateViewControllerWithIdentifier:@"TMCommodityDetailController"];
    vc.rid = model.url;
    [self.navigationController pushViewController:vc animated:YES];
}
//- (void)addTeacher{
//    SLBarCodeViewController *vc = [[UIStoryboard storyboardWithName:@"QRCode" bundle:nil] instantiateViewControllerWithIdentifier:@"SLBarCodeViewController"];
//    [self.navigationController pushViewController:vc animated:YES];
//}
#pragma tab delegate data
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!self.localArray.count) {
        return 0;
    }
    return self.localArray.count +1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        TMADCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMADCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[TMADCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TMADCell"];
        }
        [cell addSubview:self.adView];
        return cell;
    }
    if (indexPath.row == 1) {
        TMHomeOthersCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMHomeOthersCell"];
        cell.types = self.localArray[3];
        cell.block = ^(NSInteger index) {
            TMItemPageController *vc = STORY_BOARD(@"Home", @"TMItemPageController");
            TMRecommendModel *models = self.localArray[3][index];
            vc.cid = models.fid;
            vc.lists = self.localArray[3];
            vc.selectIndex = index;
            [self.navigationController pushViewController: vc animated:YES];
        };
        return cell;
    }
    if (indexPath.row == 2) {
        TMPoiResultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMPoiResultCell"];
        cell.isRecommend = YES;
        cell.modelArray = self.localArray[1];
        cell.block = ^(NSUInteger code,NSInteger fid){
            if (code == 1) {
                TMCommodityDetailController *vc = [[UIStoryboard storyboardWithName:@"Nearby" bundle:nil] instantiateViewControllerWithIdentifier:@"TMCommodityDetailController"];
                vc.rid = fid;
                [self.navigationController pushViewController:vc animated:YES];
            }
        };
        return cell;
    }
    if (indexPath.row == 3) {
        TMADCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMADCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[TMADCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TMADCell"];
        }
        UIView * view = [cell viewWithTag:10000];
        [view removeFromSuperview];
        
        UIImageView *images = [[UIImageView alloc]init];
        images.tag = 10000;
        [cell addSubview:images];
        images.contentMode = UIViewContentModeScaleAspectFill;
        images.clipsToBounds = YES;
        [images mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell).offset(11);
            make.bottom.equalTo(cell).offset(-16);
            make.width.equalTo(cell);
            make.centerX.equalTo(cell.contentView);
            
        }];

        images.image = [UIImage imageNamed:@"广告1"];
        if (self.adList) {
            TMBarnerModel * model = self.adList.lastObject;
            [images sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithBaseUrl:model.pic]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                
            }];
        }
        return cell;
    }
    if (indexPath.row == 4) {
        TMPoiResultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMPoiResultCell"];
        [cell.typeCellBtn setImage:[UIImage imageNamed:@"当地机构"] forState:UIControlStateNormal];
        cell.isRecommend = NO;
        cell.modelArray = self.localArray[2];
        cell.block = ^(NSUInteger code, NSInteger fid) {
            if (code == 0) {
                TMShopHomeController *vc = [[UIStoryboard storyboardWithName:@"Nearby" bundle:nil] instantiateViewControllerWithIdentifier:@"TMShopHomeController"];
                vc.shopid = fid;
                [self.navigationController pushViewController:vc animated:YES];
            }
        };
        cell.isHavePrice = YES;
        return cell;
    }
    return [UITableViewCell new];
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 140*kWindowW/375;
    }
    if (indexPath.row == 1) {
        return 239*kWindowW/375;
    }
    if (indexPath.row == 2) {
        return 193*kWindowW/375;
    }
    if (indexPath.row == 3) {
        return 159*kWindowW/375;
    }
    if (indexPath.row == 4) {
        return 180*kWindowW/375;
    }
    return 0.01f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.adList) {
        TMBarnerModel * model = self.adList.firstObject;
        TMCommodityDetailController *vc = [[UIStoryboard storyboardWithName:@"Nearby" bundle:nil] instantiateViewControllerWithIdentifier:@"TMCommodityDetailController"];
        vc.rid = model.url;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}



- (IBAction)rightBtenClick:(UIButton *)sender {
   
}
- (void)displayLocationManager{
    self.locationManager = [[AMapLocationManager alloc] init];
    //设置精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //设置定位超时时间
    self.locationManager.locationTimeout = 10;
    //设置反地理编码超时时间
    self.locationManager.reGeocodeTimeout = 10;
    //请求定位
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error) {
            NSLog(@"%@", error.localizedDescription);
        }
        //打印定位到的位置坐标  location:(40.037471,116.370002)
        NSLog(@"location:(%f,%f)", location.coordinate.latitude,location.coordinate.longitude);
        self.coor2d = [NSString stringWithFormat:@"%f,%f", location.coordinate.latitude, location.coordinate.longitude];
        [self getData];
        if (regeocode) {
            //反地理编码,打印定位到的地址信息  reGeocode:北京市海淀区东升镇庄盛百货(清河店)
            NSLog(@"reGeocode:%@", regeocode.formattedAddress);
            [self geoCode:regeocode.formattedAddress];
            [_searchVC.addressBtn setTitle:regeocode.city forState:UIControlStateNormal];
        }
        
    }];
}
- (void)getData{
    [self.viewModel getHomePageDataWithParam:self.coor2d Success:^(id respon1, id respon2) {
        self.adList = respon1[0];
        [self loadMainADdata];
        //            self.recommendArray = respon1[1];
        //            self.localArray = respon1[2];
        //            self.types = respon1[3];
        self.localArray = respon1;
        [self.homeTab reloadData];
       // [self.homeTab.mj_header endRefreshing];
    } Failed:^(NSString *error) {
        //[self.homeTab.mj_header endRefreshing];
    }];
}
- (DXLAddressPickView *)pickerView
{
    if (!_pickerView) {
        _pickerView = [[DXLAddressPickView alloc] init];
    }
    return _pickerView;
}
- (void)leftAction{
    [self pickerView];
    [_pickerView show];
    __weak typeof(self) weakSelf =  self;
    _pickerView.determineBtnBlock = ^(NSString *shengId, NSString *shiId, NSString *xianId, NSString *shengName, NSString *shiName, NSString *xianName, NSString *postCode) {
        NSString * text = [shengName isEqualToString:shiName] ?[NSString stringWithFormat:@"%@%@",shengName,xianName] : [NSString stringWithFormat:@"%@%@%@",shengName,shiName,xianName];
        [weakSelf geoCode:text];
        [weakSelf.searchVC.addressBtn setTitle:xianName forState:UIControlStateNormal];
    };
}
@end
